package blockchain.block;

import java.util.ArrayList;

// 区块链类
public class Blockchain {
    public ArrayList<Block> chain;
    // 初始化创世区块
    public Blockchain() {
        chain = new ArrayList<>();
        chain.add(createGenesisBlock());
    }
    // 创建创世区块
    private Block createGenesisBlock() {
        return new Block("Genesis Block", "0");
    }
    // 添加新块
    public void addBlock(String productData) {
        //Block previousBlock  = chain.getLast();
        Block previousBlock = chain.get(chain.size() - 1);
        Block newBlock = new Block(productData, previousBlock.getHash());
        chain.add(newBlock);
    }
    // 验证区块链完整性
    public boolean isChainValid() {
        for(int i=1; i < chain.size(); i++) {
            Block currentBlock = chain.get(i);
            Block previousBlock = chain.get(i-1);
            if(!currentBlock.getHash().equals(currentBlock.calculateHash())) { // 检查当前区块哈希是否正确
                return false;
            }
            if(!currentBlock.getPreviousHash().equals(previousBlock.getHash())) {// 检查与前⼀个区块的链接
                return false;
            }
        }
        return true;
    }
    // 查询农产品溯源记录
    public void queryProduct(String productId) {
        for(Block block : chain) {
            if(block.getData().contains("\"productId\":\"" + productId + "\"")) {
                System.out.println("溯源记录：" + block.getData());
            }
        }
    }

    public static void main(String[] args) {
        // 1. 初始化区块链
        Blockchain agriChain = new Blockchain();
        // 2. 添加农产品记录
        agriChain.addBlock("{"
                + "\"productId\":\"P001\","
                + "\"name\": \"有机苹果\","
                + "\"origin\": \"⼭东农场\","
                + "\"timestamp\": \"2023-09-20\""
                + "}");
        agriChain.addBlock("{"
                + "\"productId\":\"P001\","
                + "\"action\": \"运输\","
                + "\"location\": \"北京仓库\","
                + "\"temperature\": \"4℃\""
                + "}");
        agriChain.addBlock("{"
                + "\"productId\":\"P001\","
                + "\"action\": \"运输\","
                + "\"location\": \"霍州仓库\","
                + "\"temperature\": \"4℃\""
                + "}");
        // 3. 验证区块链
        System.out.println("区块链是否有效: " + agriChain.isChainValid());
        // 4. 查询溯源
        System.out.println("\n=== 产品P001溯源记录 ===");
        agriChain.queryProduct("P001");

        agriChain.chain.get(1).data = "{"
                + "\"productId\":\"P001\","
                + "\"action\": \"运输\","
                + "\"location\": \"山西仓库\","
                + "\"temperature\": \"4℃\""
                + "}";
        System.out.println("\n=== 产品P001溯源记录 ===");
        agriChain.queryProduct("P001");
        System.out.println("区块链是否有效: " + agriChain.isChainValid());
    }
}
